package com.flyqiu.flow.model.format.flowable;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Element;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class FlowableSequenceFlowFormat extends DefaultFlowableElementFormat {

    @Override
    public String xmlElementType() {
        return "sequenceFlow";
    }

    protected void elementToJson(Element element, List<Attribute> unProcessedAttrs, Map<String, Attribute> elementAttrMap, JSONObject result) {
        List<Element> conditionExpressions = element.elements("conditionExpression");
        if (conditionExpressions == null || conditionExpressions.isEmpty()) return;
        JSONArray conditions = new JSONArray();
        for (Element conditionExpression : conditionExpressions) {
            JSONObject condition = bpmnFormat.getElementFormat(conditionExpression.getName()).elementToJson(bpmnFormat, conditionExpression);
            String conditionString = condition.getString("#" + conditionExpression.getName());
            condition.remove("#" + conditionExpression.getName());
            condition.put("scriptExpression", conditionString);
            conditions.add(condition);
        }
        result.put("conditionExpression", conditions);
    }

    @Override
    protected void jsonToElement(JSONObject jsonElement, Set<String> unProcessedKeys, Element srcElement) {
        super.jsonToElement(jsonElement, unProcessedKeys, srcElement);
        if (!jsonElement.containsKey("conditionExpression")) {
            return;
        }
        JSONArray conditionExpression = jsonElement.getJSONArray("conditionExpression");
        for (int i = 0; i < conditionExpression.size(); i++) {
            JSONObject item = conditionExpression.getJSONObject(i);
            String expression = item.getString("scriptExpression");
            item.remove("scriptExpression");
            DefaultFlowableElementFormat elementFormat = bpmnFormat.getElementFormat("conditionalExpression");
            Element element = elementFormat.jsonToElement(bpmnFormat, item, srcElement);
            element.addText(expression);
        }
    }
}
